#include "flatlistmodel.h"
#include <QStandardItem>
#include <QDebug>
#include <QDataStream>
#include "TreeView.h"
FlatListModel::FlatListModel(QObject* parent) : QStandardItemModel(parent)
{
    setColumnCount(3); // 设置三列：Name, Value, Type
    setHorizontalHeaderLabels({ "Name", "Value", "Type" });
}

void FlatListModel::setRootInfo(QSharedPointer<info> rootInfo) {
    m_rootInfo = rootInfo;
    m_flatList.clear();
    dfsExpand(m_rootInfo, m_flatList);

    clear(); // 清空现有模型

    for (const auto& pair : m_flatList) {
        QSharedPointer<info> item = pair.first;
        QStandardItem* nameItem = new QStandardItem(item->m_name);
        QStandardItem* valueItem = new QStandardItem(item->m_value.toString());
        QStandardItem* typeItem = new QStandardItem(eTypeName(item->m_eType));

        // 存储序列化后的 Info 数据和路径信息
        QByteArray byteArray;
        QDataStream stream(&byteArray, QIODevice::WriteOnly);
        serializeTreeNode(item.data(), stream);
        nameItem->setData(byteArray, Qt::UserRole + 1); // 存储序列化后的 Info 数据
        nameItem->setData(QVariant::fromValue(pair.second.path), Qt::UserRole + 2); // 存储路径信息

        appendRow({ nameItem, valueItem, typeItem });
    }
}

void FlatListModel::updateAAAA()
{
    m_flatList.clear();
    dfsExpand(m_rootInfo, m_flatList);

    clear(); // 清空现有模型

    for (const auto& pair : m_flatList) {
        QSharedPointer<info> item = pair.first;
        QStandardItem* nameItem = new QStandardItem(item->m_name);
        QStandardItem* valueItem = new QStandardItem(item->m_value.toString());
        QStandardItem* typeItem = new QStandardItem(eTypeName(item->m_eType));

        // 存储序列化后的 Info 数据和路径信息
        QByteArray byteArray;
        QDataStream stream(&byteArray, QIODevice::WriteOnly);
        serializeTreeNode(item.data(), stream);
        nameItem->setData(byteArray, Qt::UserRole + 1); // 存储序列化后的 Info 数据
        nameItem->setData(QVariant::fromValue(pair.second.path), Qt::UserRole + 2); // 存储路径信息

        appendRow({ nameItem, valueItem, typeItem });
    }
}

bool FlatListModel::updateInfoByPath(const QList<int>& path, const QVariant& newValue, int column) {
    QSharedPointer<info> targetInfo = findInfoByPath(m_rootInfo, path);
    if (targetInfo) {
        switch (column) {
        case 0: // 更新 Name 列
            targetInfo->m_name = newValue.toString();
            break;
        case 1: // 更新 Value 列
            targetInfo->m_value = newValue;
            break;
        case 2: // 更新 Type 列
            targetInfo->m_eType = static_cast<eType>(newValue.toInt());
            break;
        default:
            return false;
        }
        qDebug() << "After update, node name:" << targetInfo->m_name
            << ", value:" << targetInfo->m_value.toString()
            << ", type:" << eTypeName(targetInfo->m_eType);
        // 找到对应的行索引并更新视图
        for (int row = 0; row < rowCount(); ++row) {
            QVariant storedPath = index(row, 0).data(Qt::UserRole + 2);
            if (storedPath.canConvert<QList<int>>() && storedPath.value<QList<int>>() == path) {
                emit dataChanged(index(row, column), index(row, column));
                break;
            }
        }
        emit dataUpdated(path, newValue, column);
        return true;
    }
    return false;
}

void FlatListModel::dfsExpand(const QSharedPointer<info>& node, QList<QPair<QSharedPointer<info>, PathInfo>>& flatList, const QList<int>& currentPath) {
    if (!node) return;

    flatList.append(qMakePair(node, PathInfo{ currentPath }));

    int childIndex = 0;
    for (const auto& child : node->m_children) {
        dfsExpand(child, flatList, currentPath + QList<int>{childIndex});
        ++childIndex;
    }
}

QString FlatListModel::eTypeName(eType type) {
    switch (type) {
    case eGroup: return "Group";
    case eRecorder: return "Recorder";
    case eChanel: return "Channel";
    default: return "Unknown";
    }
}

// 查找指定路径的 Info 对象
QSharedPointer<info> FlatListModel::findInfoByPath(QSharedPointer<info> node, const QList<int>& path) {
    if (path.isEmpty())
        return node;

    if (path.size() == 1)
        return node->m_children[path.first()];

    if (path.size() > 1 && path.first() < node->m_children.size()) {
        return findInfoByPath(node->m_children[path.first()], path.mid(1));
    }

    return nullptr;
}

Qt::ItemFlags FlatListModel::flags(const QModelIndex& index) const {
    if (!index.isValid())
        return Qt::NoItemFlags;

    Qt::ItemFlags defaultFlags = QStandardItemModel::flags(index);
    if (index.column() >= 0 && index.column() <= 2) // 允许编辑前三列（Name, Value, Type）
        defaultFlags |= Qt::ItemIsEditable;

    return defaultFlags;
}

bool FlatListModel::setData(const QModelIndex& index, const QVariant& value, int role) {
    if (role != Qt::EditRole || index.column() < 0 || index.column() > 2)
        return QStandardItemModel::setData(index, value, role);

    QVariant data = index.siblingAtColumn(0).data(Qt::UserRole + 2); // 获取路径信息
    if (data.canConvert<QList<int>>()) {
        QList<int> path = data.value<QList<int>>();
        if (updateInfoByPath(path, value, index.column())) {
            // 更新视图显示
           // emit dataChanged(index, index);
            updateAAAA();
            return true;
        }
    }

    return false;
}